<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/core.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";

$connection = db_open ();

$q = isset ($_GET['q']) || !empty ($_GET['q']) ? mysql_real_escape_string ($_GET['q']) : "[root]";

/* Get site name */
$result = mysql_query ("SELECT sitename FROM ".db_maketablename ($table_settings)." LIMIT 1");
if (mysql_num_rows ($result) > 0)
  {
    $row = mysql_fetch_array ($result);
    $sitename = htmlentities ($row['sitename'], ENT_COMPAT, "UTF-8", false);
  }
mysql_free_result ($result);

/* Get xmlfeed and template */
$tbl_pages = db_maketablename ($table_pages);
$tbl_templates = db_maketablename ($table_templates);
$result = mysql_query ("SELECT xmlfeed, xslt, template FROM $tbl_pages LEFT JOIN $tbl_templates ON $tbl_templates.id=$tbl_pages.template WHERE path LIKE '$q' ORDER BY path");
if (mysql_num_rows ($result) > 0)
  {
    $row = mysql_fetch_array ($result);
    $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".encodehtml (stripslashes ($row['xmlfeed']));
    $layout = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".stripslashes ($row['xslt']);
    $template_id = $row['template'];
  }
mysql_free_result ($result);

/* Prepare the XSL processor */
$doc = new DOMDocument ();
$xslproc = new XSLTProcessor ();

/* Set various parameters */
$xslproc->setParameter ("", "sitename", $sitename);

/* Set the styles parameters */
$styles = db_maketablename ($table_styles);
$styles_rel = db_maketablename ($table_styles_rel);

$result = mysql_query ("SELECT name, identifier, linked, css FROM $styles_rel LEFT JOIN $styles on $styles.id=$styles_rel.style_id WHERE template_id='$template_id'");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        if ($row['linked'] == 1)
          $xslproc->setParameter ("", $row['identifier'], "./style.php?s={$row['name']}.css");
        else
          $xslproc->setParameter ("", $row['identifier'], $row['css']);
      }
  }
mysql_free_result ($result);

/* Load and import the layout */
$doc->loadXML ($layout);
$xslproc->importStyleSheet ($doc);

/* Load the xmlfeed */
$doc->loadXML ($xmldata);

/* Print the page */
print $xslproc->transformToXML ($doc);

db_close ($connection);
?>
